package cn.edu.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class JDBCUtils {
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    public static Connection connection = null;
    static {

        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");

        try {
            driver = bundle.getString("driver");
        } catch (Exception e) {
            System.out.println("空指针异常");
        }
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");
        //驱动注册
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接，如果返回null则表示未连接成功
     * @return
     */
    public static Connection getConnection(){
        try {
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 负责关闭连接
     * @param connection
     */
    public static void close(Connection connection){
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

}
